package com.hj.ct.db.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.hj.ct.db.DBConstants;
import com.hj.ct.model.User;

public class UserDao extends SQLBaseDao {

	public UserDao(Context context) {
		super(context);
	}

	/**
	 * 插入数据
	 * 
	 * @param message
	 */
	public void insertUser(User user) {
		db = dbHelper.getWritableDatabase();
		db.beginTransaction();
		ContentValues values = getCV(user);
		db.insert(DBConstants.SQL_USER_TABLE, null, values);
		db.setTransactionSuccessful();
		db.endTransaction();
		db.close();
	}

	public ContentValues getCV(User user) {
		ContentValues values = new ContentValues();
		values.put("userName", user.getUserName());
		values.put("password", user.getPassword());
		return values;
	}

	/**
	 * 删除数据
	 * 
	 * @param message
	 */
	public void deleteUser(String userName) {
		db = dbHelper.getWritableDatabase();
		db.beginTransaction();
		db.delete(DBConstants.SQL_USER_TABLE, "userName=?", new String[] { userName });
		db.setTransactionSuccessful();
		db.endTransaction();
		db.close();
	}
	/**
	 * 删除用户密码
	 * 
	 * @param message
	 */
	public void deleteUserPassword(String userName) {
		db = dbHelper.getWritableDatabase();
		db.beginTransaction();
		db.update(DBConstants.SQL_USER_TABLE, getCV(new User(userName, "")), "userName=?", new String[] { userName });
		db.setTransactionSuccessful();
		db.endTransaction();
		db.close();
	}

	public User getUser(String userName) {
		db = dbHelper.getReadableDatabase();
		Cursor cursor = db.query(DBConstants.SQL_USER_TABLE, null, "userName=?", new String[] { userName }, null, null, "id asc");
		User user = null;
		if (cursor.moveToFirst()) {
			user = new User();
			user.setUserName(cursor.getString(cursor.getColumnIndex("userName")));
			user.setPassword(cursor.getString(cursor.getColumnIndex("password")));
		}
		db.close();
		return user;
	}

	public List<User> getUsers() {
		db = dbHelper.getReadableDatabase();
		List<User> users = new ArrayList<User>();
		Cursor cursor = db.query(DBConstants.SQL_USER_TABLE, null, null, null, null, null, "id asc");
		while (cursor.moveToNext()) {
			User user = new User();
			user.setUserName(cursor.getString(cursor.getColumnIndex("userName")));
			user.setPassword(cursor.getString(cursor.getColumnIndex("password")));
			users.add(user);
		}
		db.close();
		return users;
	}
}
